<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * 用户管理（人员信息）
 */
class User extends CI_Controller {
    
    public function __construct() {
        parent::__construct();
        $this->load->model("user_model");
        $this->load->model("role_model");
        $this->load->model("user_role_model");
        $this->load->helper('form');
        $this->load->helper('string');
        $this->load->library('form_validation');
    }

    /**
     * 用户列表
     * @param type $page
     */
    public function index($page = 1)
	{
        $conditions = array(
            'keyword' => trim($this->input->post('keyword')),
        );

        $this->config->load('pagination', true);
        $pagination = $this->config->item('pagination');
        $pagination['base_url'] = site_url('user/index');
        $pagination['total_rows'] = $this->user_model->fetch_count($conditions);
        $this->load->library('pagination', $pagination);
        
        $data = array(
            'title' => '人员信息 - 人员列表',
            'operations' => array(
                array('label' => '添加人员', 'uri' => 'user/create'),
            ),
            'conditions' => $conditions,
            'users' => $this->user_model->fetch_array($conditions, $pagination['per_page'], $page),
            'pagelink' => $this->pagination->create_links()
        );

		$this->load->view('header', $data);
        $this->load->view('user/list', $data);
        $this->load->view('footer');
	}
    
    /**
     * 添加用户
     */
    public function create() {
        
        $data = array(
            'title' => '人员信息 - 添加人员',
            'operations' => array(
                array('label' => '人员列表', 'uri' => 'user')
            )
        );
        
        if (count($_POST) > 0)
		{
            /* 有提交数据 */
            $user_roles = $this->_get_form_user_roles();

            $this->_set_form_validation_rules();
            if ($this->form_validation->run()) {
                /* 插入数据 */
                $user = $this->_get_form_user();
                $user['u_salt'] = random_string('alnum', 6);
                $this->user_model->insert($user);
                $user['u_name'] = $this->user_model->u_name();
                $u_id = $this->user_model->insert_id();

                foreach ($user_roles as $user_role) {
                    $user_role['ur_uid'] = $u_id;
                    $this->user_role_model->insert($user_role);
                }
                
                $data['sucess_message'] = '您已成功添加了人员 ' . $user['u_name'];
                $data['operations'][] = array('label' => '再次添加人员', 'uri' => 'user/create');
                $this->load->view('header', $data);
                $this->load->view('footer');
                
                return;
            }
		} else {
            $user_roles = array();
        }

        /* 显示添加表单 */
        $data['action'] = 'user/create';
        $data['user'] = $this->user_model->new_user();
        $data['roles'] = $this->role_model->fetch_array();
        $data['user_roles'] = $user_roles;
        $this->load->view('header', $data);
        $this->load->view('user/form', $data);
        $this->load->view('footer');
    }
    
    /**
     * 修改用户
     * @param type $id
     */
    public function update($id) {
        $user = $this->user_model->get($id);
        if (empty($user)) {
            /* 用户不存在 */
            show_404();
        }
        
        $data = array(
            'title' => '人员信息 - 修改人员 - ' . $user['u_name'],
            'operations' => array(
                array('label' => '人员列表', 'uri' => 'user')
            )
        );
        
        if (count($_POST) > 0)
		{
            /* 有提交数据 */
            $user_roles = $this->_get_form_user_roles();

            $this->_set_form_validation_rules($id);
            if ($this->form_validation->run()) {
                /* 验证通过，更新数据 */
                $user = $this->_get_form_user();
                $user['u_salt'] = random_string('alnum', 6);
                $this->user_model->update($id, $user);
                
                $this->user_role_model->delete_batch_by_user($id);
                foreach ($user_roles as $user_role) {
                    $user_role['ur_uid'] = $id;
                    $this->user_role_model->insert($user_role);
                }
                
                $data['sucess_message'] = '您已成功修改了人员 ' . $user['u_name'];
                $data['operations'][] = array('label' => '再次修改人员', 'uri' => 'user/update/' . $id);
                $this->load->view('header', $data);
                $this->load->view('footer');
                
                return;
            }
		} else {
            /* 没有提交数据 */
            $user_roles = array();
            $rows = $this->user_role_model->fetch_array(array('uid' => $id));
            foreach ($rows as $row) {
                $user_roles[$row['ur_rid']] = array(
                    'ur_rid' => $row['ur_rid'],
                    'ur_first_date' => $row['ur_first_date'],
                    'ur_last_date' => $row['ur_last_date'],
                );
            }
        }
        
        /* 显示修改表单 */
        $data['action'] = 'user/update/' . $id;
        $data['user'] = $user;
        $data['roles'] = $this->role_model->fetch_array();
        $data['user_roles'] = $user_roles;
        $this->load->view('header', $data);
        $this->load->view('user/form', $data);
        $this->load->view('footer');
    }
    
    /**
     * 删除用户
     * @param type $id
     */
    public function remove($id) {
        $user = $this->user_model->get($id);
        if (empty($user)) {
            /* 客户不存在 */
            show_404();
        }
        
        // TODO 判断能否删除
        
        $data = array(
            'title' => '人员信息 - 删除人员 - ' . $user['u_name'],
            'operations' => array(
                array('label' => '人员列表', 'uri' => 'user')
            )
        );
        
        $this->user_model->delete($id);
        $this->user_role_model->delete_batch_by_user($id);
                
        $data['sucess_message'] = '您已成功删除了人员 ' . $user['u_name'];
        $this->load->view('header', $data);
        $this->load->view('footer');

    }
    
    /**
     * 个人资料
     * 修改密码
     */
    public function view() {
        $id = $this->session->userdata('uid');
        
        $data = array(
            'title' => '个人资料',
        );
        
        if (count($_POST) > 0)
		{
            /* 有提交数据 */
            $this->_set_view_form_validation_rules($id);
            if ($this->form_validation->run()) {
                /* 验证通过，更新数据 */
                $user = $this->_get_view_form_user();
                $user['u_salt'] = random_string('alnum', 6);
                $this->user_model->update($id, $user);
                
                $data['sucess_message'] = '您已成功修改了密码';
            }
		}
        
        /* 显示表单 */
        $user = $this->user_model->get($id);
        $user_roles = $this->user_role_model->fetch_array(array('uid' => $id));
        $roles = $this->role_model->fetch_array();

        $data['action'] = 'user/view';
        $data['user'] = $user;
        $data['user_roles'] = $user_roles;
        $data['roles'] = $roles;
        $this->load->view('header', $data);
        $this->load->view('user/view', $data);
        $this->load->view('footer');
    }

    /**
     * 从表单取用户信息
     * @return array
     */
    private function _get_form_user() {
        $in = $this->input;
        
        return array(
            'u_name' => $in->post('u_name'),
            'u_password' => $in->post('u_password'),
            'u_first_date' => $in->post('u_first_date'),
            'u_last_date' => $in->post('u_last_date'),
            'u_real_name' => $in->post('u_real_name'),
            'u_sex' => $in->post('u_sex'),
            'u_telephone' => $in->post('u_telephone'),
        );
    }
    
    /**
     * 从个人资料表单取用户信息
     * @return array
     */
    private function _get_view_form_user() {
        $in = $this->input;
        
        return array(
            'u_password' => $in->post('u_password'),
        );
    }
    
    /**
     * 从表单取用户角色信息
     * @return array
     */
    private function _get_form_user_roles() {
        $in = $this->input;

        if ($in->post('ur_rid') == FALSE) {
            return array();
        }
        
        $ur_rids        = $in->post('ur_rid');
        $ur_first_dates = $in->post('ur_first_date');
        $ur_last_dates  = $in->post('ur_last_date');
        
        $user_roles = array();
        foreach ($ur_rids as $ur_rid) {
            $user_roles[$ur_rid] = array(
                'ur_rid' => $ur_rid,
                'ur_first_date' => $ur_first_dates[$ur_rid],
                'ur_last_date' => $ur_last_dates[$ur_rid],
            );
        }
        
        return $user_roles;
    }
    
    /**
     * 设置表单验证规则：修改用户
     * @param type $id 用户id
     */
    private function _set_form_validation_rules($id = 0) {
        // 是否需要验证密码
        $need_validate_password = ($id == 0) || $this->input->post('reset_password') !== false;
        
        $fv = $this->form_validation;
        $fv->set_rules('u_name', '', 'trim');
        $fv->set_rules('reset_password', '', '');
        $fv->set_rules('u_password', '口令', ($need_validate_password ? 'required|' : '') . 'matches[u_password_again]|min_length[6]');
        $fv->set_rules('u_password_again', '再输一次', '');
        $fv->set_rules('u_first_date', '', 'trim');
        $fv->set_rules('u_last_date', '', 'trim');
        $fv->set_rules('u_real_name', '姓名', "required|is_unique[users.u_real_name.u_id.$id]");
        $fv->set_rules('u_sex', '', 'trim');
        $fv->set_rules('u_telephone', '', 'trim');
    }
    
    /**
     * 设置表单验证规则：修改密码
     * @param type $id 用户id
     */
    private function _set_view_form_validation_rules($id = 0) {
        $fv = $this->form_validation;

        $fv->set_rules('old_password', '原密码', 'required|callback_password_check');
        $fv->set_rules('u_password', '新密码', 'required|matches[u_password_again]|min_length[6]');
        $fv->set_rules('u_password_again', '再输一次', '');
    }
    
    /**
     * 验证原密码
     * @param type $old_password
     * @return boolean
     */
    public function password_check($old_password) {
        $u_name = $this->session->userdata('uname');
        
        if (!$this->user_model->validate($u_name, $old_password)) {
            $this->form_validation->set_message('password_check', '原密码输入错误.');
            return false;
        }
        
        return true;
    }
}